from flask import render_template, session, current_app, jsonify, g, request, abort

from info.lib.Decorator.Decorator_init import user_login
from info.models import *
from info.utlis.response_code import *
from . import news_blu


@news_blu.route('/<int:new_id>')
@user_login
def news_detail(new_id):
    # 取到当前的登陆状态
    user = g.user



    news_list = []
    # 展示右侧新闻
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        return jsonify(errno=RET.DBERR, errmsg='数据库查询失败')
    news_list_li = []
    news_dict = dict()
    for news in news_list:
        news = news.to_dict()
        news_list_li.append(news)
        if news['id'] == new_id:
            news_dict = news

    # 新闻页面展示
    try:
        news = News.query.get(new_id)
    except Exception as e:
        current_app.logger.debug(e)
        return jsonify(errno=RET.DBERR, errmsg='1')

    is_instance = ''
    if user:
        user_collect_news = user.collection_news

        # 判断是否在收藏列表中
        if news in user_collect_news:
            # 表示已关注
            is_instance = True
    else:
        # 表示未关注
        is_instance = False


    # 取到所有新闻评论
    try:
        news_list = Comment.query.filter(Comment.news_id == new_id).all()
    except Exception as e:
        current_app.logger.debug(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')

    comment_list = []
    # 抽出所有评论信息
    for comment in news_list:
        comment = comment.to_dict()
        comment_list.append(comment)



    print(is_instance)

    date = {
        "user_id": user.to_dict() if user else None,# 登陆用户信息
        "news_id": news_list_li,# 右侧新闻排行信息
        'news': news_dict,# 当前右侧新闻点击
        'news_content': news.to_dict(), # 当前新闻信息
        'is_instance': is_instance,# 显示收藏状态开关
        'comments': comment_list
    }

    return render_template('news/detail.html', date=date)


@news_blu.route('/news_collect', methods=['POST'])
@user_login
def news_collect():
    """
    1 判断是否登陆
    2 获取新闻ID
    3 获取收藏状态
    4 判断收藏状态
    5 查询news_id
    :return:
    """
    user = g.user

    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登陆')
    # 取到请求参数
    news_id = request.json.get('news_id')# 取到当前新闻ID
    action = request.json.get('action')# 取道收藏状态
    # 判断是否有参数
    if not all([news_id, action]):
        return jsonify(errno=RET.NODATA, errmsg='无参数')
    # 判断请求合法
    try:
        news_id = int(news_id)
    except Exception as e:
        current_app.logger.debug(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    # 判断收藏状态是否合理
    if action not in ('collect', 'cancel_collect'):
        return jsonify(errno=RET.DATAERR, errmsg='参数错误')
    # 查询新闻数据
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.debug(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询失败')
    current_app.logger.debug(news)
    # 判断新闻数据是否存在
    if not news:
        return jsonify(errno=RET.DATAERR, errmsg='数据错误')
    user_collect_news = user.collection_news

    # 添加收藏
    if action == 'collect':
        if news not in user_collect_news:
            user_collect_news.append(news)
    # 取消收藏
    else:
        if news in user.collection_news:
            user.collection_news.remove(news)
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存失败")
    return jsonify(errno=RET.OK, errmsg='ok')


# 评论路由
@news_blu.route('/news_comment' ,methods=['POST'])
@user_login
def news_comment():
    """
    1 获取参数（评论内容，新闻ID，用户id，回复的ID,）(news_id,comment,perent_id)
    2 判断参数
    :return:
    """
    # 获取用户登陆状态
    user = g.user

    # 判断登陆状态
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登陆')

    news_id = request.json.get('news_id')  # 新闻ID
    comment = request.json.get('comment')  # 新闻内容
    perent_id = request.json.get('parent_id') # 父评论

    # 判断参数是否为空
    if not all([news_id, comment]):
        return jsonify(errno=RET.NODATA, errmsg='无参数')

    # 判断是否为数字
    try:
        news_id = int(news_id)
    except Exception as e:
        return jsonify(errno=RET.PARAMERR, errmsg='不合理请求')

    # # 查询用户信息
    # try:
    #     user_id = User.query.get(user.id)
    # except Exception as e:
    #     current_app.logger.debug(e)
    #     return jsonify(errno=RET.DBERR, errmsg='数据库查询失败')

    # 初始化评论对象
    info_comment = Comment()
    info_comment.user_id = user.id
    info_comment.content = comment
    info_comment.news_id = news_id

    # 判断父级ID
    if perent_id:
        info_comment.parent_id = perent_id
    # 添加到数据库中
    try:
        db.session.add(info_comment)
        db.session.commit()
    except Exception as e:
        current_app.logger.debug(e)
        return jsonify(errno=RET.DATAERR, errmsg='提交失败')
        print("-"*50)
        print(user.id)

    # dete={
    #     'discuss':info_comment.to_dict(),
    #     'user':user
    # }

    return jsonify(errno=RET.OK, errmsg='评论成功', date=info_comment.to_dict())


# 点赞！
@news_blu.route('/comment_like', methods=['POST'])
@user_login
def comment_like():
    """
    1 获取参数（news_di,comment_id,action）
    2 校验参数
    3 添加点赞
    4 返沪参数

    :return:
    """
    user = g.user

    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登陆')

    # 获取参数
    news_id = request.json.get('news_id')
    comment_id = request.json.get('comment_id')
    action = request.json.get('action')

    # 判断是否有值
    if not all([news_id,comment_id,action]):
        return jsonify(errno=RET.NODATA, errmsg='无数据')

    # 判断action是否合理
    if action not in ('add','remove'):
        return jsonify(errno=RET.REQERR, errmsg='非法请求')

    # 查询评论列表
    try:
        comment = Comment.query.filter(Comment.news_id == news_id).first()
    except Exception as e:
        current_app.logger.debug(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询失败')

    # 评论是否存在
    if not comment:
        return jsonify(errno=RET.NODATA, errmsg='无数据')

    # 该评论是否在当前用户的点赞列表下
    try:
        comment_list = CommentLike.query.filter(CommentLike.user_id == user.id, CommentLike.comment_id == comment.id).first()
    except Exception as e:
        current_app.logger.debug(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询失败')

    comment_like = CommentLike()


    # 判断点赞状态
    if action == 'add':
        # 判断该用户是否已经点过赞
        if not comment_list:
            comment_like.user_id = user.id
            comment_like.comment_id = comment.id
            # 点赞计数
            comment.like_count += 1

    else:
        if comment_list:
            db.session.delete(comment_list)


    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.debug(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询失败')


    return jsonify(errno=RET.OK, errmsg='点赞成功')























